package com.xmjs.baselibrary.base.activity.permission;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.xmjs.baselibrary.view.dialog.ExSweetAlertDialog;
import com.xmjs.baselibrary.view.swipeback.SwipeBackActivity;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Action;

/**
 * 该基类的作用：
 * 1.支持权限申请和处理
 */
public class PermissionActivity extends SwipeBackActivity {
    private Action mPermissionSuccessAcion;
    private String mPermissionDescription;
    private List<String> needPermissions = new ArrayList<>();//需要申请的权限列表
    private static final int MY_PERMISSIONS_REQUEST = 1001;
    private static final String PACKAGE_URL_SCHEME = "package:";
    private static final int REQUEST_CODE_REQUEST_SETTING = 1027;

    /**
     * 请求权限
     *
     * @param permissions               权限列表
     * @param action                    获得权限成功之后的回调
     * @param needPermissionDescription 需要这些权限的原因（当用户拒绝之后，会提示这个原因）
     */
    public void requestPermission(String[] permissions, Action action, @StringRes int needPermissionDescription) {
        try {
            requestPermission(permissions, action, getResources().getString(needPermissionDescription));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 请求权限
     *
     * @param permissions               权限列表
     * @param action                    获得权限成功之后的回调
     * @param needPermissionDescription 需要这些权限的原因（当用户拒绝之后，会提示这个原因）
     */
    public void requestPermission(String[] permissions, Action action, String needPermissionDescription) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                needPermissions.add(permission);
            }
        }
        if (needPermissions == null || needPermissions.size() <= 0) {//已经获得权限，直接执行
            try {
                action.run();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        boolean needRationale = false;//是否需要权限的原因。当申请的权限被用户拒绝之后，再次申请时会提示
        for (String p : needPermissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, p)) {
                needRationale = true;
                break;
            }
        }

        mPermissionSuccessAcion = action;//获得权限之后的回调
        mPermissionDescription = needPermissionDescription;//申请权限的描述信息

        if (needRationale) {//提示之后再申请权限
            new ExSweetAlertDialog(this, ExSweetAlertDialog.AlertDialogType.NORMAL_TYPE)
                    .setTitleText("权限申请")
                    .setContentText(needPermissionDescription)
                    .setConfirmClickListener(dialog -> {
                        ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[0]), MY_PERMISSIONS_REQUEST);
                        dialog.dismissWithAnimation();
                    }).show();
        } else {//直接申请权限
            ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[0]), MY_PERMISSIONS_REQUEST);
        }
    }

    /**
     * 请求权限之后的回调处理
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        try {
            if (requestCode == MY_PERMISSIONS_REQUEST) {
                boolean allGranted = true;
                for (int result : grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        allGranted = false;
                    }
                }
                if (allGranted) {//已获得全部权限
                    if (mPermissionSuccessAcion != null)
                        mPermissionSuccessAcion.run();
                } else {//未获得权限，提示是否打开设置页面
                    if (!TextUtils.isEmpty(mPermissionDescription)) {
                        new ExSweetAlertDialog(this, ExSweetAlertDialog.AlertDialogType.ERROR_TYPE)
                                .setTitleText("权限申请失败")
                                .setContentText(mPermissionDescription + "\n是否前往设置？")
                                .setCancelText("取消")
                                .setConfirmText("确认")
                                .setConfirmClickListener(dialog -> {
                                    startAppSettings(this);
                                    dialog.dismissWithAnimation();
                                })
                                .setCancelClickListener(dialog -> {
                                    dialog.dismissWithAnimation();
                                    this.finish();
                                }).show();
                    }
                }
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回该页面时的回调处理
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == REQUEST_CODE_REQUEST_SETTING) {
                List<String> list = new ArrayList<>();
                for (String permission : needPermissions) {
                    if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) {
                        list.add(permission);
                    }
                }
                if (list.size() > 0) {
                    if (!TextUtils.isEmpty(mPermissionDescription)) {
                        new ExSweetAlertDialog(this, ExSweetAlertDialog.AlertDialogType.ERROR_TYPE)
                                .setTitleText("权限申请失败")
                                .setContentText(mPermissionDescription + "\n是否前往设置？")
                                .setCancelText("取消")
                                .setConfirmText("确认")
                                .setConfirmClickListener(dialog -> {
                                    startAppSettings(this);
                                    dialog.dismissWithAnimation();
                                })
                                .setCancelClickListener(dialog -> {
                                    dialog.dismissWithAnimation();
                                    this.finish();
                                }).show();
                    }
                } else {
                    if (mPermissionSuccessAcion != null)
                        mPermissionSuccessAcion.run();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到app的设置页面去设置权限
     */
    private void startAppSettings(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + activity.getPackageName()));
        activity.startActivityForResult(intent, REQUEST_CODE_REQUEST_SETTING);
    }

}
